package com.qqtech.qquan.user.controller;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.qqtech.core.common.annotation.VisitAnnt;
import com.qqtech.core.common.enums.RespEnum;
import com.qqtech.core.common.enums.YesNoEnum;
import com.qqtech.core.common.util.StringUtil;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.model.Result;
import com.qqtech.core.frame.service.BaseService;
import com.qqtech.qquan.circle.service.CircleMemberService;
import com.qqtech.qquan.community.service.CommunityJoinService;
import com.qqtech.qquan.draw.service.DrawBaseService;
import com.qqtech.qquan.draw.service.DrawBatchService;
import com.qqtech.qquan.draw.service.DrawItemService;
import com.qqtech.qquan.user.enums.UserRelationTypeEnum;
import com.qqtech.qquan.user.enums.UserValueOsTypeDictEnum;
import com.qqtech.qquan.user.model.UserValue;
import com.qqtech.qquan.user.model.UserValueQuery;
import com.qqtech.qquan.user.model.UserValueVo;
import com.qqtech.qquan.user.service.UserBaseService;
import com.qqtech.qquan.user.service.UserDrawService;
import com.qqtech.qquan.user.service.UserFriendService;
import com.qqtech.qquan.user.service.UserValueService;
import com.qqtech.web.context.BaseWebController;

@Controller
@RequestMapping(value = "/user/value")
public class UserValueController extends BaseWebController<UserValue, UserValueQuery> {
	
	@Resource
	private UserValueService userValueService;
	@Resource
	private UserFriendService userFriendService;
	@Resource
	private CircleMemberService circleMemberService;

	@Resource
	private CommunityJoinService communityJoinService;
	@Resource
	private DrawBaseService drawBaseService;

	@Resource
	private DrawItemService drawItemService;

	@Resource
	private DrawBatchService drawBatchService;

	@Resource
	private UserDrawService userDrawService;

	@Resource
	private UserBaseService userBaseService;

	private Integer TALENT_RANK = 3;//发帖达人
	private Integer MONTH_RANK = 2;//月榜
	private Integer WEEKLY_RANK = 1;//周榜
	private Integer HONOR_RANK = 0;//荣耀榜
	private Integer WEEKLY_DAY = 7;
	private Integer MONTH_DAY = 30;

	@Override
	protected BaseService<UserValue> getBaseService() {
		return userValueService;
	}

	@RequestMapping(value = "/changeBg")
	@ResponseBody
	public Result changeBg(@RequestBody Map<String, String> map) {
		Result ret = new Result();
		Integer curUserId = super.getUserId();
		String isBackground = map.get("isBackground");
		String osType = map.get("osType");
		if (curUserId != null && curUserId.intValue() != 0 && StringUtil.isNotBlank(isBackground)) {
			UserValue userValue = new UserValue();
			userValue.setId(curUserId);
			int isBg = 0;
			if (("" + YesNoEnum.YES.getCode()).equals(isBackground)) {
				isBg = 1;
			} else if (("" + YesNoEnum.NO.getCode()).equals(isBackground)) {
				isBg = 2;
			}
			if (isBg != 0) {
				userValue.setIsBackground(isBg);
				if (StringUtil.isNotBlank(osType)) {
					userValue.setOsType(new Integer(osType));
				}
				userValueService.updateById(userValue);
			}
		}
		return ret;
	}

	/**
	 * 附近的人-按距离查询（从近到远）
	 * 
	 * @param userValueQuery
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/nearbyUsers")
	@ResponseBody
	public Result nearbyUsers(@RequestBody UserValueQuery userValueQuery) {
		Result result = new Result();
		Integer curUserId = super.getUserId();

		if (userValueQuery == null) {
			result.addErr("参数不能为空");
		} else if (userValueQuery.getX() == null || userValueQuery.getY() == null) {
			result.addErr("请选择定位");
		}
		if (!result.checkForm()) {
			return result;
		}

		// **设置用户位置信息begin**/
		UserValue userValue = null;
		if (curUserId != null) {
			userValue = userValueService.getById(curUserId);
		}
		if (userValue == null) {
			if (curUserId != null) {
				userValue = new UserValue();
				userValue.setId(curUserId);
				userValue.setMoney(0);
				userValue.setX(userValueQuery.getX());
				userValue.setY(userValueQuery.getY());
				userValue.setIsBackground(YesNoEnum.NO.getCode());
				userValue.setIsShowLocation(YesNoEnum.NO.getCode());
				userValue.setOsType(UserValueOsTypeDictEnum.ANDROID.getCode());
				userValueService.insert(userValue);
			}
		} else {
			if (curUserId != null && userValueQuery.getX() != null && userValueQuery.getY() != null
					&& (userValue.getX() == null || userValue.getY() == null
							|| userValueQuery.getX().compareTo(userValue.getX()) != 0
							|| userValueQuery.getY().compareTo(userValue.getY()) != 0)) {
				UserValue updateUserValue = new UserValue();
				updateUserValue.setId(userValue.getId());
				updateUserValue.setX(userValueQuery.getX());
				updateUserValue.setY(userValueQuery.getY());
				userValueService.updateById(updateUserValue);
			}
		}
		// **设置用户位置信息end**/

		List<Integer> myFriendIds = userFriendService.queryMyFriendIds(curUserId);
		if (myFriendIds == null) {
			myFriendIds = Lists.newArrayList();
		}
		myFriendIds.add(0);
		List<Integer> myNeigborIds = communityJoinService.getNeighborUserIds(curUserId);
		if (myNeigborIds == null) {
			myNeigborIds = Lists.newArrayList();
		}
		myNeigborIds.add(0);
		if (!userValueService.isShowLocation(curUserId)) {
			// 如果没有显示定位,就打开
			userValueService.setShowLocation(curUserId, true);
		}
		List<Integer> userIds = Lists.newArrayList();
		userIds.add(curUserId);
		userValueQuery.setExcludeUserIds(userIds);// 排除我自己
		Integer relationType = userValueQuery.getRelationType();// 用户关系
		if (relationType != null) {
			if (relationType == UserRelationTypeEnum.FRIEND.getCode()) {// 好友
				userValueQuery.setIncludeUserIds(myFriendIds);// 只查我的好友
			} else if (relationType == UserRelationTypeEnum.NEIGBOR.getCode()) {
				userValueQuery.setIncludeUserIds(myNeigborIds);// 只查我的邻居
			}
		}

		userValueQuery.setIsShowLocation(YesNoEnum.YES.getCode());
		Pageable pageKit = new PageKit(userValueQuery.getPage(), new PageOrder(Direction.ASC, "distance"));
		Page<UserValueVo> page = userValueService.queryPageListByDistance(userValueQuery, pageKit);
		List<Integer> outCircleIds = Lists.newArrayList();// 共同加入圈子ID列表

		List<UserValueVo> userList = page.getContent();
		if (userList != null && userList.size() > 0) {
			for (UserValueVo user : userList) {
				outCircleIds = circleMemberService.queryOurcircleIds(curUserId, user.getId());// 他的圈子ID列表
				user.setOurCircleCount(outCircleIds.size());// 共同加入圈子数量
				if (myFriendIds.contains(user.getId())) {
					user.setFriend(true);// 是圈友关系
				}
				if (myNeigborIds.contains(user.getId())) {
					user.setNeighbor(true);// 邻居关系
				}
				if (user.getId() == curUserId) {
					user.setOurCircleCount(0);// 我自己，先临时这样处理
				}
			}
		}

		result.put("page", page);
		return result;
	}

	/**
	 * 显示定位信息
	 * 
	 * @param id
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/checkXY")
	@ResponseBody
	public Result checkXY() {
		Result ret = new Result();
		Integer curUserId = super.getUserId();
		UserValue userValue = userValueService.getById(curUserId);
		ret.put("userValue", userValue);
		return ret;
	}

	/**
	 * 显示定位信息
	 * 
	 * @param id
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/addDrawCount")
	@ResponseBody
	public Result addDrawCount() {
		Result ret = new Result();
		Integer curUserId = super.getUserId();
		int updateConut = userValueService.updateDrawCount(curUserId);
		boolean hasDrawCount = false;
		if (updateConut > 0) {
			hasDrawCount = true;
		}
		ret.put("hasDrawCount", hasDrawCount);
		return ret;
	}

	/**
	 * 显示定位信息
	 * 
	 * @param id
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/showLocation")
	@ResponseBody
	public Result showLocation() {
		Result ret = new Result();
		Integer curUserId = super.getUserId();
		int updateCount = userValueService.setShowLocation(curUserId, true);
		if (updateCount != 1) {
			ret.addErr("显示定位信息失败");
		}
		return ret;
	}

	/**
	 * 隐藏定位信息
	 * 
	 * @param id
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/hideLocation")
	@ResponseBody
	public Result hideLocation() {
		Result ret = new Result();
		Integer curUserId = super.getUserId();
		userValueService.setShowLocation(curUserId, false);
		return ret;
	}

	/**
	 * 查询-是否显示定位
	 * 
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/isShowLocation")
	@ResponseBody
	public Result isShowLocation() {
		Result ret = new Result();
		Integer curUserId = super.getUserId();
		boolean isShowLocation = userValueService.isShowLocation(curUserId);
		ret.put("isShowLocation", isShowLocation);
		return ret;
	}
	
	/**
	 * 管理列表
	 * 
	 * @param 
	 * @return
	 */
	@RequestMapping(value = "/page")
	@ResponseBody
	public Result page(@RequestBody UserValueQuery userValueQuery) {
		Result result = new Result();
		if(userValueQuery.getCommunityId() == null || userValueQuery.getCommunityId() ==0 ){
			result.addErr("社区Id不能为空");
			return  result;
		}
		userValueQuery.setPage(1);
		userValueQuery.setSize(50);
		if(userValueQuery.getRankType() == TALENT_RANK){
			Pageable pageKit = new PageKit(userValueQuery.getPage(), userValueQuery.getSize(), new PageOrder(Direction.DESC, "c.mount") );
			Page<UserValueVo> page = userValueService.queryPageListByTalent(userValueQuery, pageKit);
			result.put("page", page);
			return result;
		}
		if(userValueQuery.getRankType() == WEEKLY_RANK || userValueQuery.getRankType() == MONTH_RANK){
			Date date = new Date();
			userValueQuery.setEndTime(new Timestamp(date.getTime()));
			userValueQuery.setStartTime(new Timestamp(subDate(date,WEEKLY_DAY).getTime()));
			if(userValueQuery.getRankType() == MONTH_RANK){
				userValueQuery.setStartTime(new Timestamp(subDate(date,MONTH_DAY).getTime()));
			}
		}
		Pageable pageKit = new PageKit(userValueQuery.getPage(), userValueQuery.getSize(), new PageOrder(Direction.DESC, "honorValue"), new PageOrder(Direction.DESC, "u.id"));
		Page<UserValueVo> page = userValueService.queryUserInfo(userValueQuery, pageKit);
		result.put("page", page);
		return result;
	}

	private Date subDate(Date date, int day) {
		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(date.getTime() - ((long) day) * 24 * 3600 * 1000);
		return c.getTime();
	}
}
